const { MongoClient } = require('mongodb');
const WebSocket = require('ws');
const mongoose = require('mongoose');
const uri = "mongodb+srv://nikiisme321:t36T3Qp1aFjqTFPq@cluster0.k7soc.mongodb.net/el";
const client = new MongoClient(uri);
mongoose
    .connect("mongodb+srv://nikiisme321:t36T3Qp1aFjqTFPq@cluster0.k7soc.mongodb.net/el")
    .then(() => {
        console.log('ok')
    })
    .catch((err) => {
        console.log(err)
    })

//用户表
let userSchema = new mongoose.Schema({
    name: String, //昵称
    real_name: { type: String, default: "佚名" },//真实姓名
    password: String,//密码
    phone: String,//手机号
    id_card: { type: String, default: "" }, //身份证号
    avater: { type: String, default: "https://pic1.zhimg.com/50/v2-6afa72220d29f045c15217aa6b275808_720w.jpg?source=1940ef5c" }, //用户头像
    create_date: { type: Date, default: Date.now() }, //创建时间
})

// 每日金价走势图
const historyFundSchema = new mongoose.Schema({
    date: Number,
    time: String,
    avg_price: Number,
    price: Number,
    volume: Number
});
// 每日金价走势图-模型
const HistoryFund = mongoose.model('HistoryFund', historyFundSchema,'historyfunds');
const database = client.db('el');
const newHistoryFundModel = database.collection('newHistoryFunds');
// 实时金价
const QuoteSchema = new mongoose.Schema({
    q68: String,
    q124: String,
    q67: String,
    q64: String,
    q193: String,
    q1: String,
    q2: String,
    q3: String,
    q4: String,
    q5: String,
    q6: String,
    q70: String,
    q7: String,
    q8: String,
    q9: String,
    q10: String,
    q11: String,
    q12: String,
    q13: String,
    q14: String,
    q15: String,
    q16: String,
    q80: String,
    q17: String,
    q18: String,
    q19: String,
    q20: String,
    q21: String,
    q22: String,
    q23: String,
    q24: String,
    q60: String,
    q61: String,
    q62: String,
    q63: String,
    q59: String,
});
// 实时金价-模型
const Quote = mongoose.model('Quote', QuoteSchema,'quotes');
// 今日的
const TodayQuote = new mongoose.Schema({
    time: String,
    price: String
})
const TodayQuoteModel = mongoose.model('TodayQuote', TodayQuote)
// 周数据
const WeekQuoteSchema = new mongoose.Schema({
    q68: String,
    q124: String,
    q67: String,
    q1: String,
    q3: String,
    q4: String,
    q2: String,
    q60: String,
    q62: String,
    qhistoryStyle: String,
    q64: String,
    q193: String,
    q5: String,
    q6: String,
    q70: String,
    q7: String,
    q8: String,
    q9: String,
    q10: String,
    q11: String,
    q12: String,
    q13: String,
    q14: String,
    q15: String,
    q16: String,
    q80: String,
    q17: String,
    q18: String,
    q19: String,
    q20: String,
    q21: String,
    q22: String,
    q23: String,
    q24: String,
    q61: String,
    q63: String,
    q59: String,
})
const WeekQuoteModel = mongoose.model('WeekQuote', WeekQuoteSchema)
// 月数据
const MonthQuoteSchema = new mongoose.Schema({
    q68: String,
    q124: String,
    q67: String,
    q1: String,
    q3: String,
    q4: String,
    q2: String,
    q60: String,
    q62: String,
    qhistoryStyle: String,
    q64: String,
    q193: String,
    q5: String,
    q6: String,
    q70: String,
    q7: String,
    q8: String,
    q9: String,
    q10: String,
    q11: String,
    q12: String,
    q13: String,
    q14: String,
    q15: String,
    q16: String,
    q80: String,
    q17: String,
    q18: String,
    q19: String,
    q20: String,
    q21: String,
    q22: String,
    q23: String,
    q24: String,
    q61: String,
    q63: String,
    q59: String,
})
const MonthQuoteModel = mongoose.model('MonthQuote', MonthQuoteSchema)
// 年数据
const YearQuoteSchema = new mongoose.Schema({
    date: String,
    type: String,
    open: Number,
    max: Number,
    min: Number,
    close: Number
})
const YearQuoteModel = mongoose.model('YearQuote', YearQuoteSchema)
// 创建WebSocket服务器
const wss = new WebSocket.Server({ port: 3001 });
wss.on('connection', (ws) => {
    console.log('WebSocket client connected');
    ws.on('message', async (message) => {
        try {
            console.log('Received message:', message);  // 打印接收到的原始消息
            const data = JSON.parse(message); //解析JSON数据
            console.log('Parsed data:', data);  // 打印解析后的数据
            // 存储今日数据
            if (Array.isArray(data) && data[0].date && data[0].time) {
                try {
                    await HistoryFund.deleteMany({})
                    await HistoryFund.insertMany(data)
                    console.log(data[0, 10], '存储历史数据');
                } catch (error) {
                    console.error('Error saving data:', error);
                }
            }
            // 存储实时数据
            if (data.q68 && data.q124 && data.q67) {  // 判断是否有实时数据字段
                const newQuote = new Quote({
                    q68: data.q68,
                    q124: data.q124,
                    q67: data.q67,
                    q64: data.q64,
                    q193: data.q193,
                    q1: data.q1,
                    q2: data.q2,
                    q3: data.q3,
                    q4: data.q4,
                    q5: data.q5,
                    q6: data.q6,
                    q70: data.q70,
                    q7: data.q7,
                    q8: data.q8,
                    q9: data.q9,
                    q10: data.q10,
                    q11: data.q11,
                    q12: data.q12,
                    q13: data.q13,
                    q14: data.q14,
                    q15: data.q15,
                    q16: data.q16,
                    q80: data.q80,
                    q17: data.q17,
                    q18: data.q18,
                    q19: data.q19,
                    q20: data.q20,
                    q21: data.q21,
                    q22: data.q22,
                    q23: data.q23,
                    q24: data.q24,
                    q60: data.q60,
                    q61: data.q61,
                    q62: data.q62,
                    q63: data.q63,
                    q59: data.q59,
                });
                try {
                    await Quote.deleteMany({})
                    await newQuote.save();
                    console.log('Real-time data saved:', data);
                } catch (error) {
                    console.error('Error saving real-time data:', error);
                }
            }
            // 周数据
            if (data.length == 100 && data[0].q68 && data[0].q124 && data[0].q67 && data[0].q1) {
                try {
                    await WeekQuoteModel.deleteMany({})
                    await WeekQuoteModel.insertMany(data)
                    console.log(data[0, 10], '存储周数据');
                } catch (error) {
                    console.error('Error saving data:', error);
                }
            }
            // 月数据
            if (data.length == 260 && data[0].q68 && data[0].q124 && data[0].q67 && data[0].q1) {
                try {
                    await MonthQuoteModel.deleteMany({})
                    await MonthQuoteModel.insertMany(data)
                    console.log(data[0, 10], '存储月数据');
                } catch (error) {
                    console.error('Error saving data:', error);
                }
            }
            // 今日数据-2
            // if (data.time && data.price) {
            // 如果是数组，逐条保存到 TodayQuoteModel 中
            // for (const entry of data) {
            //   if (entry.time && entry.price) {
            //     // const newTodayQuote = new TodayQuoteModel({
            //     //   time: entry.time,
            //     //   price: entry.price
            //     // });
            //     try {
            //       await TodayQuoteModel.insertMany(data)
            //       console.log('Stored today quote:', data);
            //       return
            //     } catch (error) {
            //       console.error('Error saving today quote:', error);
            //     }
            //   } else {
            //     console.warn('Invalid data format:', data);
            //   }
            // }
            // }
        } catch (err) {
            console.error('Error processing message:', err);
        }

    });
    ws.on('close', () => {
        console.log('WebSocket client disconnected');
    });
    ws.on('error', (error) => {
        console.error('WebSocket error:', error);
    });
});
console.log('WebSocket server running at ws://localhost:3001');






//黄金基金表
// const goldSchema = new mongoose.Schema({
//     fundName: String,//基金名称
//     fundCode: String,//基金代码
//     description: String,//基金描述
//     currentPrice: Number,//当前每克黄金价格
//     priceHistory: Array,//历史价格数据（数组，每个元素包含日期和价格）
//     createdAt: Date,//创建时间
//     updatedAt: Date,//更新时间
// })
//交易表
const tradeSchema = new mongoose.Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user'
    },
    transactionType: {//交易类型
        type: String,
        enum: ['buy', 'sell'],
        default: 'buy'
    },
    transactionAmount: Number,//交易金额，用户需要支付的金额
    goldAmount: Number,//买入或卖出的黄金克数，买入后不会改变
    pricePerGram: Number,//买入或卖出时的每克黄金价格
    status: { //交易状态
        type: String,
        enum: ['pending',//待确认
            'confirmed',//已确认,确认金价
            'completed',//已完成，确认买入
            'cancelled'//已取消
        ]
    },
    priceConfirmationDate: {
        type: Date,
        default: null
    },//确认金价格日期和时间（3点之前当天，3点之后以T+1日收盘价为准）
    buyConfirmationDate: {
        type: Date,
        default: null
    },//确认买入日期和时间（买入后两天确认，周五3点后买入周一确认金价，周二确认并开始收益）
    createdAt: {
        type: Date,
        default: new Date()
    },//记录创建日期和时间
})
//持仓表--每天根据黄金基金的涨跌更新 goldAmount 和 totalAmount
const positionSchema = new mongoose.Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user'
    },
    goldAmount: Number,//当前持有的黄金克数，买入后不会改变
    buyPrice: Number,//买入或卖出时的每克黄金价格
    totalAmount: Number,//当前持仓的总金额，每天更新，根据克数*当前黄金价格变化
    createdAt: Date,//创建日期和时间
})
//收益表
const profitSchema = new mongoose.Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user'
    },
    positionId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'position'
    },//收益表关联持仓表
    dailyEarnings: [//记录每日收益信息
        {
            date: {
                type: Date,
                default: new Date()
            },//收益日期
            earnings: Number,//当日收益金额
            earningsRate: Number,//当日收益率（可选）
        },
    ],
    totalEarnings: {
        type: Number,
        default: 0
    },//累计收益金额，购买基金以来累计的收益金额,持有收益
    totalRate: {
        type: Number,
        default: 0
    },//累计收益率，购买基金以来累计的收益率，持有收益率
    lastUpdated: {
        type: Date,
        default: new Date()
    }, // 最后更新时间
    status: {
        type: String,
        enum: ['active', 'closed'],
        default: 'active'
    }, // 收益记录状态，active表示收益记录有效，closed表示收益记录已关闭
})
//黄金价格历史表
const goldHerstorySchema = new mongoose.Schema({
    date: Date,//价格记录的日期
    price: Number,//每克黄金价格
})
// 定期投资表
const recurringInvestmentSchema = new mongoose.Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user',
        required: true
    },
    investmentAmount: {
        type: Number,
        required: true // 定投金额
    },
    frequency: {
        type: String,
        enum: ['每日', '每周', '每两周', '每月'],
        required: true // 'daily', 'weekly', 'biweekly', 'monthly'
    },
    weekDays: { // 当 frequency 为 'weekly' 或 'biweekly' 时使用
        type: String,
        enum: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
        default: null
    },
    monthDays: { // 当 frequency 为 'monthly' 时使用
        type: Number,
        min: 1,
        max: 28,
        default: null
    },
    startDate: {
        type: Date,
    },
    endDate: Date, // 可选的结束日期
    status: {
        type: String,
        enum: ['active', 'cancelled', 'stopped'],
        default: 'active'
    },
    createdAt: {
        type: Date,
        default: new Date()
    },
    updatedAt: {
        type: Date,
        default: new Date()
    }
});
const realTimeRatioSchema = new mongoose.Schema({
    date: { type: String, unique: true }, // 日期（唯一标识）
    bullRatio: { type: Number, default: 0 }, // 看涨比例
    bearRatio: { type: Number, default: 0 }, // 看跌比例
    updateTime: { type: Date, default: Date.now }, // 更新时间
});

// 创建 RealTimeRatio 模型
const RealTimeRatio = mongoose.model('RealTimeRatio', realTimeRatioSchema);

// 定义 TransactionChoice 模型
const transactionChoiceSchema = new mongoose.Schema({
    userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, // 引用 User 模型的用户 ID
    choiceType: { type: String, enum: ['bull', 'bear'], required: true }, // 选择类型，'bull' 表示看涨，'bear' 表示看跌
    choiceTime: { type: Date, default: Date.now }, // 选择时间，默认为当前时间
    choiceStatus: { type: String, enum: ['active', 'canceled'], default: 'active' }, // 选择状态，默认为 'active'
    date: { type: String }, // 日期字段
    realTimeRatioId: { type: mongoose.Schema.Types.ObjectId, ref: 'RealTimeRatio' }, // 关联 RealTimeRatio 模型的 ID
});

// 为 userId 和 date 字段建立唯一索引，确保一个用户在同一天只能做一次选择
transactionChoiceSchema.index({ userId: 1, date: 1 }, { unique: true });

// 创建 TransactionChoice 模型
const TransactionChoice = mongoose.model('TransactionChoice', transactionChoiceSchema);


let RefreshTokenSchema = new mongoose.Schema({
    token: { type: String, unique: true },
    expiresAt: {
        type: Date,
        default: () => Date.now() + 7*24*60*60 * 1000 // 设置 Token 有效期为7tian
    },
    uid: {
        type: mongoose.Types.ObjectId,
        ref: "userr" // 确保引用的用户模型名称正确
    }
});

// 编译模型后，创建 TTL 索引
RefreshTokenSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });

let tokenModel = mongoose.model("refreshToken", RefreshTokenSchema, 'refreshToken')

//---------------------------商品-----------------------------
const AlipaySdk = require('alipay-sdk').default
const alipaySdk = new AlipaySdk({
    appId: "9021000133633257",
    signType: "RSA2",  //签名算法
    gateway: "https://openapi-sandbox.dl.alipaydev.com/gateway.do",//支付宝网关地址
    alipayPublicKey: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiGeSEyzCoUUNblwT3DCRn8hRPIrD19VgAaKuZMSSF2aXrPlnjDD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Fxa69rfYHdnhcx94638X5ziWDRzDNghTQ/Cxr3WW2ItVM/9a8daVV8tw8Cea0YaNfWWxtHNh8xrHIoh7RjjRZzYDv6AIZmSs+11S7LAJVqPP8jCjrz6AC4TYhvdbFX/MrZWWHvGy+zloPFEydn4Y7FHaTv+fcLCkQKBgQChdTzmSuEN7L2HCblslvLklyXVenmXW7ADo/VNcqWQOwCYxlRfdUGUOtP7lquXF+shf2j/5TL3i3j/2G0z3pjq+psqLF3hbghOsxlka8s/KNm4GI8ReslX7/Kd5nSbffZbkJq0xWLgIykCrePWhR2yTPn9dw/hZNhTulGF4elNXwKBgCRL9ySrUL/gng3AstcpvK3Y3hUtDE2zBwhcqQXNqmnRTVQL3PO/wO5xbVpOnFQZn2RFxse6JVMPXfjMgzmLG/QWzO87B4xYHd221+T+MlDCJnahU6I9hq0x0u93xTZ0FIcnVGWGZrlWK76FhaundmuMqUHs+7PhFxlk3ow+7eWhAoGAbwAq3iickPYxVqVY1U7xrjY7zIhnD6f5WodeHeCz8nSd9GpllzsF2uKW2mC7lyTagi0WAteQMp+wkDQ6324ps2KXSmc2I8WB8Jkw29k/4iwzgl1f/qRryAkuw1+syznOJSVFNwJ895s0lqL2AIWD5REGzTsNr+ek0etGIMUvoAECgYEA59LcKAnC4RbrzxBQ4nBEg5sKlXEHA+hK7eC1BVeyk9mnjs37olPhgQMkRzvZOaPLvW8BfK22xToGWaC013wuKkxhFui2IcJchfalmX5F1sDnU5b+RqCza04aZzOWfiXgYGMazBIKYfh8rRDgBsjCI/dC7A/jOVTrZW1nL3BU2zQ=',//应用私钥
})
module.exports = alipaySdk
//商品表
const ProductSchema = new mongoose.Schema({
    name: String,//商品名称
    price: Number,//价格
    grams: Number,//克数
    images: String,//图片
    sales: Number,//销量
    description: String,//描述
    like: {
        type: Boolean,
        default: false
    },//收藏
    num: {
        type: Number,
        default: 1
    },//数量
    purity: {
        type: Number,
        default: 0
    }//纯度
})

//地址表
const AddressSchema = new mongoose.Schema({
    name: String,//收货人
    phone: String,//电话
    area: String,//地区
    details: String,//详细地址
    isDefault: {
        type: Boolean,
        default: false
    },//是否默认
    cid: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user'
    }//用户id
})

//订单表
const OrderSchema = new mongoose.Schema({
    cid: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user'
    },//用户id
    pid: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'product'
    },//商品id
    num: Number,//数量
    price: Number,//价格
    status: {
        type: String,//订单状态
        default: 'Pending'
    },
    address: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'address'
    },
    orderId: String,
    createdAt: { type: Date, default: Date.now },
    proname: String,
    grams: Number,
    images: String,
    priceone: Number,
})



const OrderModel = mongoose.model('order', OrderSchema, "order")
const ProductModel = mongoose.model('product', ProductSchema, "product")
const AddressModel = mongoose.model('address', AddressSchema, "address")




const userModel = mongoose.model('user', userSchema, 'user')
const tradeModel = mongoose.model('trade', tradeSchema, 'trade')
const positionModel = mongoose.model('position', positionSchema, 'position')
const profitModel = mongoose.model('profit', profitSchema, 'profit')

const goldHerstoryModel = mongoose.model('goldHerstory', goldHerstorySchema, 'goldHerstory')
const recurringInvestmentModel = mongoose.model('recurringInvestment', recurringInvestmentSchema, 'recurringInvestment');

module.exports = {
    tokenModel, userModel, tradeModel, positionModel, profitModel, goldHerstoryModel, recurringInvestmentModel, TransactionChoice, RealTimeRatio, HistoryFund, Quote, TodayQuoteModel, WeekQuoteModel, MonthQuoteModel,YearQuoteModel,ProductModel,AddressModel,OrderModel
}